import { Injectable } from '@angular/core';
import { IContentComponent } from './IContentComponent';
import { ContentFormService } from './content-form.Service';
import { LazyLoadEvent } from 'primeng/api';
import {
    PagedMotherSiteContentInput,
    ContentServiceProxy,
    ContentSyncServiceProxy,
    PagedContentInput,
    PagedContentOfDictionaryOfStringObject,
    SetStatusWithMenuIdInput,
    SwapSortNumberWithMenuIdInput,
    NameValueDto,
    ManualSyncInput
} from '@shared/service-proxies/service-proxies';
import { finalize } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { MessageService } from 'abp-ng2-module';
import { AppNotifyService } from '@shared/utils/service/app-notify.service';
import { AppLocalizationService } from '@app/shared/common/localization/app-localization.service';
import { DateTimeHelper } from '@shared/helpers/DateTimeHelper';
import { AppBsModalService } from '@shared/common/appBsModal/app-bs-modal.service';
import { ManualSyncModalComponent } from '../shared/manual-sync/manual-sync-modal.component';

@Injectable()
export class AppContentService{

    constructor(
        private _contentFormService: ContentFormService,
        private _contentServiceProxy: ContentServiceProxy,
        private message: MessageService,
        private notify: AppNotifyService,
        private _contentSyncService: ContentSyncServiceProxy,
        private _modalService: AppBsModalService,
        private _appLocalizationService: AppLocalizationService) {
        
    }


    initListPage(vm: IContentComponent, callBack: { ():void}) {
        this._contentFormService.getConfigAndPermisions(vm, result => {
            vm.pageConfig = result.config;
            vm.customKey = result.config.keyName;
            vm.permissionDic = result.permissions;
            
            vm.inputPara = Object.assign(new PagedContentInput(),{
                menuId: vm.kind,
                customKey: vm.customKey,
                relateId: vm.relateId,
                infoState: '#',
                filter: '',
                maxResultCount: 10,
                skipCount: 0,
                sorting: vm.pageConfig.diyOrderBy
            });

            if (vm.contentListTab && vm.contentListTab.dataTable) {
                vm.contentListTab.dataTable.reset();
            }

            if (!vm.primengTableHelper.TryChangePage(vm.contentListTab.paginator, 0)) {
                vm.getListData(null);
            }

            if (callBack) {
                callBack();
            }
        });
    }

    //-- action

    resetListApiCache() {
        this._contentServiceProxy.resetListApiCache().subscribe(() => {
            this.notify.success(this._appLocalizationService.l('ExecuteSuccessfully'));
        });
    }

        
    reloadPage(vm: IContentComponent) {
        if (vm.primengTableHelper.TryChangePage(vm.contentListTab.paginator, vm.contentListTab.paginator.getPage())) {
            return;
        }

        vm.getListData(null);
    }

    getList(
        vm: IContentComponent,
        event?: LazyLoadEvent,
        newGetListFunc?: (body: PagedContentInput | undefined) => Observable<PagedContentOfDictionaryOfStringObject>) {

        vm.contentListTab.selectedDatas = [];

        if (vm.primengTableHelper.shouldResetPaging(event)) {
            if (vm.primengTableHelper.TryChangePage(vm.contentListTab.paginator, 0)) {
                return;
            }
        }

        vm.primengTableHelper.showLoadingIndicator();

        let input = vm.inputPara;

        if (vm.contentListTab) {
            input.maxResultCount = vm.primengTableHelper.getMaxResultCount(vm.contentListTab.paginator, event);
            input.skipCount = vm.primengTableHelper.getSkipCount(vm.contentListTab.paginator, event);
        }

        if (newGetListFunc) {
            newGetListFunc(input)
                .pipe(finalize(() => vm.primengTableHelper.hideLoadingIndicator()))
                .subscribe(result => {
                    this.processListData(vm, result);
                });
        } else {
            this._contentServiceProxy.getContentListByPaged(input)
                .pipe(finalize(() => vm.primengTableHelper.hideLoadingIndicator()))
                .subscribe(result => {
                    this.processListData(vm, result);
                });
        }
    }

    swapOrder(vm: IContentComponent){
        let params =  JSON.parse(JSON.stringify(vm.inputPara));
        params.maxResultCount = 10;
        params.skipCount = 0;

        const pIndex = vm.pageConfig.list.findIndex(t=> (t.fieldName && t.fieldName.toLocaleLowerCase() === 'publishtime'));

        let swapInput = new SwapSortNumberWithMenuIdInput({
            menuId: vm.kind,
            relateId: vm.relateId,
            idOrderList :[]
        });
        vm.orderByModal.configure({
            defaultParam: params,
            getDataFunc :(t)=>{
                return this._contentServiceProxy.getContentListByPaged(t);
            },
            getTitile : (t)=> t.title,
            getTime : (t)=> {
                if(pIndex >= 0){
                    return DateTimeHelper.FromUnixTimestampByMilliseconds(t.publishTime)
                }
                return DateTimeHelper.FromUnixTimestampByMilliseconds(t.creationTime)
            },
            getItemOrder: (t)=> t.order,
            getTotolCount :(t)=>t.totolCount,
            getItems :(t)=> t.items,
            swapOrderFunc : (t)=>{
                return this._contentServiceProxy.swapObjectSort(t);
            },
            swapOrderParam: swapInput
        });
        vm.orderByModal.show();
    }

    private processListData(vm: IContentComponent, result: PagedContentOfDictionaryOfStringObject) {
        if (!vm.isModal && vm.pageConfig.isInfo && result.isSingle) {
            vm.gotoDetail(result.items.length > 0 ? result.items[0].id : '');
        } else {
            vm.hiddenList = false;

            vm.primengTableHelper.totalRecordsCount = result.totolCount;
            vm.primengTableHelper.records = result.items;
            vm.primengTableHelper.hideLoadingIndicator();
        }
    }

    openCreateOrEdit(vm: IContentComponent, id: string) {
        vm.contentDetailModal.show(id, vm.kind, vm.customKey, vm.relateId, vm.permissionDic, vm.pageConfig);
    }

    deleteItems(vm: IContentComponent) {
        if (vm.contentListTab) {
            let idList = vm.contentListTab.getSelectedIds();
            

            if (idList.length > 0) {
                this.message.confirm(this._appLocalizationService.l('DeleteWarningMessage'), this._appLocalizationService.l('AreYouSure'),
                    (isConfirmed) => {
                        if (!isConfirmed) return;
                        this._contentServiceProxy.deleteListAysnc(vm.kind, vm.relateId, idList)
                            .subscribe(() => {
                                vm.contentListTab.selectedDatas = [];
                                vm.getListData(null);
                                this.notify.success(this._appLocalizationService.l('SuccessfullyDeleted'));
                            });
                    })
            }
        }
    }

    changeState(vm: IContentComponent, state: boolean) {
        if (vm.contentListTab) {
            let idList = vm.contentListTab.getSelectedIds();

            if (idList.length > 0) {
                let msg: string;
                if (state) {
                    msg = this._appLocalizationService.l('ReleaseWarningMessage');
                }
                else {
                    msg = this._appLocalizationService.l('UndoReleaseWarningMessage');
                }
                this.message.confirm(msg, this._appLocalizationService.l('AreYouSure'),
                    (isConfirmed) => {
                        if (!isConfirmed) return;

                        let input = new SetStatusWithMenuIdInput();
                        input.menuId = vm.kind;
                        input.idList = idList;
                        input.isActive = state;

                        this._contentServiceProxy.setStatus(input)
                            .subscribe(() => {
                                vm.getListData(null);
                                vm.contentListTab.selectedDatas = [];
                                if (state) {
                                    this.notify.success(this._appLocalizationService.l('ReleaseSuccessfully'));
                                } else {
                                    this.notify.success(this._appLocalizationService.l('CancelReleaseSuccessfully'));
                                }
                            });
                    })
            }
        }
    }

    synchorization(vm: IContentComponent) {
        const bsModalRef = this._modalService.show(ManualSyncModalComponent, {
            backdrop: 'static', class: 'modal-xl'
        });

        let params = new PagedMotherSiteContentInput();
        params.menuId = vm.kind;
        params.customKey = vm.customKey;
        params.relateId = vm.relateId;

        let keyList : NameValueDto[] = [];

        bsModalRef.content.configure({
            defaultParam: params,
            getDataFunc: (t)=> this._contentSyncService.getContentMotherInfo(t),
            getItems: (t)=> t,
            confirmFunc:(t)=> this._contentSyncService.manualContentSynchorize(t),
            keyList: keyList,
            confirmDefaultParam : new ManualSyncInput()
        });
        bsModalRef.content.shown();
        bsModalRef.content.callback = () => {
            vm.reloadPage();
        };
    }

    //-- action end
}
